Saving and loading trained Deep Learning models has multiple valuable uses. These models are often costly to train; storing a pre-trained model can help reduce costs as it can be loaded and reused to forecast multiple times. Moreover, it enables Transfer learning capabilities, consisting of pre-training a flexible model on a large dataset and using it later on other data with little to no training. It is one of the most outstanding 🚀 achievements in Machine Learning 🧠 and has many practical applications.
In this notebook we show an example on how to save and load NeuralForecast models.
The two methods to consider are: 1. NeuralForecast.save: Saves models into disk, allows save dataset and config. 2. NeuralForecast.load: Loads models from a given path.
Important
This Guide assumes basic knowledge on the NeuralForecast library. For a minimal example visit the Getting Started guide.
You can run these experiments using GPU with Google Colab.
1. Installing NeuralForecast
%%capture !pip install neuralforecast
2. Loading AirPassengers Data
For this example we will use the classical AirPassenger Data set. Import the pre-processed AirPassenger from utils.
from neuralforecast.utils import AirPassengersDFY_df = AirPassengersDFY_df = Y_df.reset_index(drop=True)Y_df.head()
unique_id
ds
y
0
1.0
1949-01-31
112.0
1
1.0
1949-02-28
118.0
2
1.0
1949-03-31
132.0
3
1.0
1949-04-30
129.0
4
1.0
1949-05-31
121.0
3. Model Training
Next, we instantiate and train three models: NBEATS, NHITS, and AutoMLP. The models with their hyperparameters are defined in the models list.
from ray import tunefrom neuralforecast.core import NeuralForecastfrom neuralforecast.auto import AutoMLPfrom neuralforecast.models import NBEATS, NHITS
[model_name]_[suffix].ckpt: Pytorch Lightning checkpoint file with the model parameters and hyperparameters.
[model_name]_[suffix].pkl: Dictionary with configuration attributes.
Where model_name corresponds to the name of the model in lowercase (eg. nhits). We use a numerical suffix to distinguish multiple models of each class. In this example the names will be automlp_0, nbeats_0, and nhits_0.
Important
The Auto models will be stored as their base model. For example, the AutoMLP trained above is stored as an MLP model, with the best hyparparameters found during tuning.
5. Load models
Load the saved models with the load method, specifying the path, and use the new nf2 object to produce forecasts.